import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';

import '../../models/models.dart';
import '../../repositories/repositories.dart';

part 'favorite_event.dart';
part 'favorite_state.dart';

class FavoriteBloc extends Bloc<FavoriteEvent, FavoriteState> {
  final ArticleRepository articleRepository;
  FavoriteBloc({
    required this.articleRepository, 
  }) : super(FavoriteInitial()) {
    on<UpdateFavoriteEvent>((event, emit) async {
      try{
        emit(FavoriteUpdate(value: !event.favorited,isUpdating: true));
        //  Article article;
         if (event.favorited) {
        await articleRepository.createFavorite(event.slug);
        } else {
         await articleRepository.deleteArticleFavorite(event.slug);
        }
        Article article=await articleRepository.getArticle(event.slug);
        emit(FavoriteUpdate(value: article.favorited, isUpdating: false));
      }catch (error){
        emit(FavoriteError(error: error));
      }
    });
  }
}
